package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.WxAppletUser;
import com.ruoyi.system.domain.vo.WxAppletRes;
import com.ruoyi.system.service.IWxAppletUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * 1、微信小程序开发接口
 * @Author: chy
 * @Date: 2022/5/20
 **/
@RestController
@RequestMapping("/api/weixin")
public class WechatController {

    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Resource
    private IWxAppletUserService wxAppletUserService;

    /**
     * 微信小程序AppID
     */
    @Value("${wx.app-id}")
    private String AppID;
    /**
     * 微信小程序AppSecret
     */
    @Value("${wx.app-secret}")
    private String AppSecret;

    /**
     * @param
     * @return
     */
    @PostMapping("/wxlogin")
    public AjaxResult getWechatLoginInfo(@RequestBody WxAppletRes wxAppletRes, HttpServletRequest request) {
        logger.info("微信登录请求入参-->wxAppletRes = [{}]",wxAppletRes);

        //查询openid
        String openid = getOpenid(wxAppletRes);
        //更新用户信息
        updateWxAppletUser(openid,wxAppletRes,request);

        String token = UUID.randomUUID().toString();
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("openid", openid);
        return AjaxResult.success(data);
    }



    private String getOpenid(WxAppletRes wxAppletRes){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String params = StringUtils.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret, wxAppletRes.getCode());
        String json = HttpUtils.sendGet(url, params);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String session_key = (String) jsonObject.get("session_key");
        String openid = (String) jsonObject.get("openid");
        if (StringUtils.isEmpty(openid)) {
            throw new ServiceException("未获取到openid");
        }
        return openid;
    }

    private void updateWxAppletUser(String openid,WxAppletRes wxAppletRes, HttpServletRequest request){
        //查询当前用户是否存在
        WxAppletUser wxAppletUser = wxAppletUserService.selectWxAppletUserByOpenId(openid);
        if (wxAppletUser == null){
            wxAppletUser = new WxAppletUser();
            wxAppletUser.setWeixinOpenid(openid);
            wxAppletUser.setAvatar(wxAppletRes.getAvatarUrl());
            wxAppletUser.setNickname(wxAppletRes.getNickName());
            wxAppletUser.setLastLoginTime(new Date());
            wxAppletUser.setLastLoginIp(IpUtils.getIpAddr(request));
            wxAppletUserService.insertWxAppletUser(wxAppletUser);
        }
        wxAppletUser.setLastLoginTime(new Date());
        wxAppletUser.setLastLoginIp(IpUtils.getIpAddr(request));
        wxAppletUserService.updateWxAppletUser(wxAppletUser);
    }


}
